#include<time.h>
#include"Socket.hpp"
#include"Protocol.hpp"

//连接服务器，然后给服务器发消息，再读消息，再把消息打印一下，循环即可

static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

//./clientcal serverip serverport 
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);

    //连接服务器
    Sock socket;
    socket.Socket();
    int r=socket.Connect(serverip,serverport);
    if(!r) 
        return 1; 

    std::string inbuffer_stream;
    //开始发送消息
    int cnt=1;
    while(cnt<10)
    {
        std::cout<<"------------第"<<cnt<<"次测试---------"<<std::endl;
        //制作请求
        srand(time(nullptr)^getpid());
        int data1=rand()%10;
        int data2=rand()%10;
        std::string opers="+-*/%";
        char op=opers[rand()%5];

        //展示请求
        Request req(data1,data2,op);
        std::cout<<req.GetRequest()<<std::endl;

        //打包请求
        std::string content;
        req.Serialize(&content);
        std::string package;
        EnCode(content,&package);

        //发送请求
        write(socket.Fd(),package.c_str(),package.size());

        //收到响应
        char buffer[1024];
        int n=read(socket.Fd(),buffer,1024);

        if(n>0)
        {
            //解包响应
            buffer[n]=0;
            inbuffer_stream+=buffer;
            std::string content;
            DeCode(inbuffer_stream,&content);
            Response rsp;
            rsp.DeSerialize(content);
            //展示响应结果    
            std::cout<<rsp.GetResult()<<std::endl;
            
        }
        else if(n==0)
        {
            std::cout<<"Server Quit!"<<std::endl;
        }
        else
        {
            exit(0);
        }
        cnt++;
        sleep(1);
    }
    socket.Close();
    return 0;
}